package com.woniuxy.thred.syn;

/**
 * description: HappCinema <br>
 * date: 2022/2/6 2:50 上午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */

/**
 * 快乐影院
 */
public class HappCinema {
    public static void main(String[] args) {
        Cinema c = new Cinema(2, "蜗牛影院");
        new Thread(new Customer(c, 2), "zs").start();
        new Thread(new Customer(c, 1), "ls").start();
    }
}

//顾客
class Customer implements Runnable {

    Cinema cinema;
    //位置
    int seats;

    public Customer(Cinema cinema, int seats) {
        this.cinema = cinema;
        this.seats = seats;
    }

    @Override
    public void run() {
        synchronized (cinema) {
            boolean flag = cinema.bookTickets(seats);
            if (flag) {
                System.out.println("出票成功" + Thread.currentThread().getName() + "-<位置为：" + seats);
            } else {
                System.out.println("出票失败" + Thread.currentThread().getName() + "-<位置不够！");
            }
        }
    }
}


//影院
class Cinema {
    //可用位置
    int available;
    //名称
    String name;

    public Cinema(int available, String name) {
        this.available = available;
        this.name = name;
    }

    //购票
    public boolean bookTickets(int seats) {
        System.out.println("可用位置：" + available);
        if (seats > available) {
            return false;
        }
        available -= seats;
        return true;
    }
}